package com.future.message.Service.Impl;

import com.future.message.Mapper.DataMapper;
import com.future.message.Mapper.IndexMapper;
import com.future.message.Mapper.RelevantReportMapper;
import com.future.message.Mapper.UserMapper;
import com.future.message.Service.DataService;
import com.future.message.Service.RelevantReportService;
import com.future.message.Utils.ResponseResult;
import com.future.message.Utils.Utils;
import com.future.message.pojo.Data;
import com.future.message.pojo.Index;
import com.future.message.pojo.RelevantReport;
import com.future.message.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RelevantReportServiceImpl implements RelevantReportService {
    @Resource
    UserMapper userMapper;
    @Resource
    RelevantReportMapper relevantReportMapper;
    @Resource
    IndexMapper indexMapper;
    @Resource
    DataMapper dataMapper;
    @Resource
    DataService dataService;

    @Override
    public ResponseResult addRelevantReport(Integer userId,Integer firstIndexId,Integer secondIndexId,Integer thirdIndexId) {
        User user= userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("改用户不存在");
        }
        Index index=indexMapper.findIndexById(firstIndexId);
        if (index == null) {
            return ResponseResult.error("该指标不存在");
        }
        ResponseResult responseResult=judgeOfRelevantReport(userId,thirdIndexId);
        if(responseResult.getObject().equals(1)){
            return ResponseResult.error("该指标分配过了");
        }
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1=simpleDateFormat.format(date);
        RelevantReport relevantReport=new RelevantReport();
        relevantReport.setFirstIndexId(firstIndexId);
        relevantReport.setSecondIndexId(secondIndexId);
        relevantReport.setThirdIndexId(thirdIndexId);
        relevantReport.setUserId(userId);
        relevantReport.setRelevantTime(date1);
        relevantReportMapper.addRelevantReport(relevantReport);
        return ResponseResult.success("添加成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteRelevantReport(Integer relevantReportId) {
        RelevantReport r= relevantReportMapper.findRelevantReportById(relevantReportId);
        if (r == null) {
            return  ResponseResult.error("该填报关联不存在");
        }
        log.info("要删除的填报关联{}",relevantReportId);
        Data data= dataMapper.findDataByRelevantReportId(relevantReportId);
        if(data != null){
            dataService.deleteData(data.getDataId());
        }
        relevantReportMapper.deleteRelevantReport(relevantReportId);
        return ResponseResult.success("删除成功");
    }


    @Override
    public ResponseResult findRelevantByUserId(Integer userId) {
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        List<RelevantReport> relevantReports= relevantReportMapper.findRelevantByUserId(userId);
        return ResponseResult.success("查找成功",relevantReports);
    }

    @Override
    public ResponseResult findAllRelevantReport() {
        List<RelevantReport> relevantReports= relevantReportMapper.findAllRelevantReport();
        return ResponseResult.success("查找成功",relevantReports);
    }

    @Override
    public ResponseResult findRelevantReportById(Integer relevantReportId) {
        RelevantReport r= relevantReportMapper.findRelevantReportById(relevantReportId);
        if (r == null) {
            return  ResponseResult.error("该填报关联不存在");
        }
        return ResponseResult.success("查找成功",r);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteRelevantList(Integer[] relevantReportId) {
        for(int x:relevantReportId){
            Data data=dataMapper.findDataByRelevantReportId(x);
            if(data!=null){
                dataService.deleteData(data.getDataId());
            }
        }
        Integer i= relevantReportMapper.deleteRelevantList(relevantReportId);
        return ResponseResult.success("删除成功",i);
    }

    @Override
    public ResponseResult findFirstIndexReport(Integer userId) {
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        HashMap<Integer, Index> hashMap=new HashMap<>();;
        Integer[] firstIndexIds=relevantReportMapper.findFirstIndexIdByUserId(userId);
        for(int x:firstIndexIds){
            Index index=indexMapper.findIndexById(x);
            hashMap.put(x,index);
        }
//        List<RelevantReport> relevantReports=relevantReportMapper.findRowNumber();
//        List<Integer> c= relevantReports.stream().map(RelevantReport::getAaa).collect(Collectors.toList());
//        List<Integer> d= relevantReports.stream().map(RelevantReport::getUserId).collect(Collectors.toList());
//        Object[]arr1= c.toArray();
//        Object[]arr2= d.toArray();
//        System.out.println(relevantReports);
//        System.out.println(c);
//        System.out.println(d);
//        HashMap<Integer,Integer> hashMap=new HashMap<>();
//        for(int i=0;i<relevantReports.size();i++){
//            hashMap.put((Integer) arr2[i],(Integer) arr1[i] );
//        }
//        System.out.println(hashMap.get(userId));
//       List<RelevantReport> relevantReport= relevantReportMapper.findFirstIndexReport(userId,hashMap.get(userId));
        return ResponseResult.success("遍历分配给用户的一级指标成功",hashMap);
    }

    @Override
    public ResponseResult findSecondIndexReport(Integer userId, Integer firstIndexId) {
        Index index=indexMapper.findIndexById(firstIndexId);
        if (index == null) {
            return ResponseResult.error("该一级指标不存在");
        }
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        HashMap<Integer, Index> hashMap=new HashMap<>();;
        Integer[] secondIndexIds=relevantReportMapper.findSecondIndexIdByUserId(userId,firstIndexId);
        for(int x:secondIndexIds){
            Index index1=indexMapper.findIndexById(x);
            hashMap.put(x,index1);
        }
//        List<RelevantReport> relevantReports=relevantReportMapper.findRowNumber();
//        List<Integer> c= relevantReports.stream().map(RelevantReport::getAaa).collect(Collectors.toList());
//        List<Integer> d= relevantReports.stream().map(RelevantReport::getUserId).collect(Collectors.toList());
//        Object[]arr1= c.toArray();
//        Object[]arr2=d.toArray();
//        System.out.println(relevantReports);
//        System.out.println(c);
//        System.out.println(d);
//        HashMap<Integer,Integer> hashMap=new HashMap<>();
//        for(int i=0;i<relevantReports.size();i++){
//            hashMap.put((Integer) arr2[i],(Integer) arr1[i] );
//        }
//        System.out.println(hashMap.get(userId));
//        List<RelevantReport> relevantReport=  relevantReportMapper.findSecondIndexReport(userId, firstIndexId,hashMap.get(userId));
        return ResponseResult.success("遍历分配给用户的二级指标成功",hashMap);
    }

    @Override
    public ResponseResult findThirdIndexReport(Integer userId, Integer secondIndexId) {
        Index index=indexMapper.findIndexById(secondIndexId);
        if (index == null) {
            return ResponseResult.error("该二级指标不存在");
        }
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        List<RelevantReport> relevantReport=relevantReportMapper.findThirdIndexReport(userId, secondIndexId);
        return ResponseResult.success("遍历分配给用户的三级指标成功",relevantReport);
    }

    @Override
    public ResponseResult judgeOfRelevantReport(Integer userId, Integer thirdIndexId) {
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        List<RelevantReport> relevantReports= relevantReportMapper.findOfRelevantReport(userId, thirdIndexId);
        if (!relevantReports.isEmpty()) {
            return ResponseResult.success("该指标已经分配过",1);
        }else{
            return ResponseResult.success("该指标为分配过",0);
        }
    }

    @Override
    public ResponseResult countIndexNumberByUserId(Integer userId) {
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        Integer i= relevantReportMapper.countIndexNumberByUserId(userId);
        System.out.println(i);
        return ResponseResult.success("查询该用户需要填写多少个指标---共有几个指标",i);
    }

    @Override
    public ResponseResult countCompleteIndexNumberByUserId(Integer userId) {
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        Integer i=relevantReportMapper.countCompleteIndexNumberByUserId(userId);
        Integer j=relevantReportMapper.countIndexNumberByUserId(userId);
        Integer unCompleteNumber=j-i;
        return ResponseResult.success("查询该用户完成了多少个指标---已完成几个指标",i,unCompleteNumber);
    }

    @Override
    public ResponseResult countIndexNumberByUserIdAndIndexId(Integer userId, Integer indexId) {
        Index index=indexMapper.findIndexById(indexId);
        if (index == null) {
            return ResponseResult.error("该二级指标不存在");
        }
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        Integer i=relevantReportMapper.countIndexNumberByUserIdAndFirstIndexId(userId,indexId);
        return ResponseResult.success("查询分配给该用户一级指标下的指标数量---该一级指标下总共有几个需要完成",i);
    }

    @Override
    public ResponseResult countCompleteIndexNumberByUserIdIndexId(Integer userId, Integer indexId) {
        Index index=indexMapper.findIndexById(indexId);
        if (index == null) {
            return ResponseResult.error("该二级指标不存在");
        }
        User user=userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        Integer i=relevantReportMapper.countCompleteIndexNumberByUserIdIndexId(userId,indexId);
        Integer j=relevantReportMapper.countIndexNumberByUserIdAndFirstIndexId(userId,indexId);
        int v=bs(i,j);
        String str=v+"%";
        return ResponseResult.success("查询分配给该用户一级指标下的完成的指标数量---该一级指标下完成了几个指标",i,str);
    }

    @Override
    public ResponseResult judgeOfReport(Integer relevantReportId) {
        RelevantReport relevantReport=relevantReportMapper.findRelevantReportById(relevantReportId);
        if (relevantReport == null) {
            return ResponseResult.error("不存在填报指标");
        }
        if(relevantReport.getOfReport()==0){
            return ResponseResult.success("该数据未填报",0);
        }else{
            return ResponseResult.success("改数据已填报",1);
        }
    }

    @Override
    public ResponseResult findThirdIndexListBySecondIndexList(Integer secondIndexId) {
        Index index=indexMapper.findIndexById(secondIndexId);
        if(index==null){
            return ResponseResult.error("该二级指标不存在");
        }
        int i=0;
        List<RelevantReport> relevantReports= relevantReportMapper.findThirdIndexListBySecondIndexList(secondIndexId);
        List<Integer> c= relevantReports.stream().map(RelevantReport::getOfReport).collect(Collectors.toList());//将集合转化为一列id
        for(int x:c){
            i=i+x;
        }
        if (i == 0) {
            return ResponseResult.success("该二级指标下所有指标都没完成",0);
        }
        if(i>0&&i<c.size()){
            return ResponseResult.success("该二级指标下的指标完成一部分",1);
        }
        if(i==c.size()){
            return ResponseResult.success("全部完成",2);
        }
        return ResponseResult.error("未知错误");
    }

    @Override
    public ResponseResult findSecondCompleteRate(Integer secondIndexId) {
        Index index=indexMapper.findIndexById(secondIndexId);
        if (index == null) {
            return ResponseResult.error("该二级指标不存在");
        }
        Integer b=relevantReportMapper.countThirdIndexBySecondIndexId(secondIndexId);
        Integer a=relevantReportMapper.countCompleteThirdIndexBySecondIndexId(secondIndexId);
        int s=bs(a,b);
        String str=s+"%";
        return ResponseResult.success("完成率为",str);
    }

    @Override
    public ResponseResult addRelevantReportByFirstIndexId(Integer userId, Integer firstIndexId) {
        Index index=indexMapper.findIndexById(firstIndexId);
        if (index == null) {
            return ResponseResult.error("该一级指标不存在");
        }
        User user =userMapper.findUserById(userId);
        if(user==null){
            return ResponseResult.error("该用户不存在");
        }
            Integer[]secondIndexIds=indexMapper.findIndexesByIndexFatherId(firstIndexId);
                for(int y:secondIndexIds){
                    Integer []thirdIndexIds=indexMapper.findIndexesByIndexFatherId(y);
                    for(int z:thirdIndexIds){
                        //添加指标
                       addRelevantReport(userId,firstIndexId,y,z);
                    }
                }
        return ResponseResult.success("分配给用户一级指标下所有指标成功");
    }

    @Override
    public ResponseResult addRelevantReportBySecondIndexId(Integer userId, Integer firstIndexId, Integer secondIndexId) {
        Index index=indexMapper.findIndexById(firstIndexId);
        if (index == null) {
            return ResponseResult.error("该一级指标不存在");
        }
        User user =userMapper.findUserById(userId);
        if(user==null){
            return ResponseResult.error("该用户不存在");
        }
                Integer []thirdIndexIds=indexMapper.findIndexesByIndexFatherId(secondIndexId);
                for(int z:thirdIndexIds){
                    //添加指标
                    addRelevantReport(userId,firstIndexId,secondIndexId,z);
                }
        return ResponseResult.success("分配二级指标下所有指标成功");
    }

    @Override
    public ResponseResult findUserByOfDistribution(Integer grade, Integer indexId) {
        Index index=indexMapper.findIndexById(indexId);
        if (index == null) {
            return ResponseResult.error("该等级指标不存在");
        }
        Integer num=0;
        if(grade==1){
            Integer[] i= indexMapper.findIndexesByIndexFatherId(indexId);//找到所有二级指标id
           for(int x:i){
                Integer thirdCount=indexMapper.countNumByIndexIdAndGrade(x,3);//根据二级指标来计数三级指标
                num=num+thirdCount;
           }

           HashMap<Integer,String> hashMap=new HashMap<>();
           Integer[]userIds=relevantReportMapper.findUserIdsByFirstIndexId(indexId);
           Object[] newUserIds=Utils.removeDuplicates(userIds);
           for(Object a:newUserIds){
               String b=a.toString();
               Integer c= Integer.valueOf(b);
               Integer relevantReportCount=  relevantReportMapper.countIndexNumberByUserIdAndFirstIndexId(c,indexId);
               if(relevantReportCount.equals(num)){
                   User user1=userMapper.findUserById(c);
                   hashMap.put(c,user1.getDepartment());
               }
           }
            return ResponseResult.success("以下用户一级指标已被分配",hashMap);
        }

        if (grade==2) {
            Integer thirdCount=indexMapper.countNumByIndexIdAndGrade(indexId,3);
            HashMap<Integer,String> hashMap=new HashMap<>();
            Integer[]userIds=relevantReportMapper.findUserIdsBySecondIndexId(indexId);
            Object[] newUserIds=Utils.removeDuplicates(userIds);
            for(Object a:newUserIds){
                String b=a.toString();
                Integer c= Integer.valueOf(b);
                Integer relevantReportCount=relevantReportMapper.countIndexNumberByUserIdAndSecondIndexId(c,indexId);
                if(relevantReportCount.equals(thirdCount)){
                    User user=userMapper.findUserById(c);
                    hashMap.put(c,user.getDepartment());
                }
            }
            return ResponseResult.success("以下用户二级级指标已被分配",hashMap);
        }

        if(grade==3){
            HashMap<Integer, RelevantReport> hashMap=new HashMap<>();
            List<RelevantReport> u=relevantReportMapper.findRelevantReportByThirdIndexId(indexId);
            List<Integer> s=u.stream().map(RelevantReport::getUserId).collect(Collectors.toList());
            for(int a:s){
                Integer relevantReportCount=relevantReportMapper.countIndexNumberByUserIdAndThirdIndexId(a,indexId);
                if(relevantReportCount==1){
                    RelevantReport relevantReport=relevantReportMapper.findRelevantReportByUserIdAndThirdIndexId(a,indexId);
                    hashMap.put(a,relevantReport);
                }
            }
        return ResponseResult.success("以下用户三级指标已被分配",hashMap);
        }

        return ResponseResult.error("指标等级错误(1-3)");
    }

    @Override
    public ResponseResult deleteReportsByIndexIdAndUserId(Integer indexId, Integer userId, Integer indexGrade) {
        Index index=indexMapper.findIndexById(indexId);
        if (index == null) {
            return ResponseResult.error("该等级指标不存在");
        }
        User user=userMapper.findUserById(userId);
        if(user==null){
            return ResponseResult.error("该用户不存在");
        }

        if(indexGrade==1){//开启一级连带删除
          Integer []firstReportIds=relevantReportMapper.findReportIdByFirstIndexIdAndUserId(indexId,userId);
            if(firstReportIds.length!=0){
                deleteRelevantList(firstReportIds);//调用上面的接口
                return ResponseResult.success("删除一级以下填报关联成功");
            }else{
                return ResponseResult.success("找不到该填报关联");
            }

        }
        if(indexGrade==2){//开启二级连带删除
        Integer[] secondReportIds= relevantReportMapper.findReportIdBySecondIndexIdAndUserId(indexId,userId);
            if(secondReportIds.length!=0){
                deleteRelevantList(secondReportIds);//调用上面的接口
                return ResponseResult.success("删除二级以下填报关联成功");
            }else{
                return ResponseResult.success("找不到该填报关联");
            }
        }
        return ResponseResult.error("指标等级填写错误,只能是1级或者2级");
    }

    /**
     * 百分率
     * @param a
     * @param b
     * @return
     */
    public int bs(int a ,int b){
        return (int)((new BigDecimal((float) a / b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())*100);
    }


}